#!/bin/bash

# !!!WARNING!!!
# This sh is used to init the .flaskenv when docker compose up the project
# Never run it yourself!!

# Check the env var
# Check the env var

if [ -z "$MYSQL_HOST" ] || [ -z "$MYSQL_PORT" ] || [ -z "$MYSQL_DATABASE" ] || [ -z "$MYSQL_USERNAME" ] || [ -z "$MYSQL_PASSWORD" ] || [ -z "$REDIS_HOST" ] || [ -z "$REDIS_PORT" ]; then
    echo "Error: Don't try to run it yourself!!!"
    echo "If you see this when do docker compose up, please check the environments in compose.yaml"
    exit 1
fi

# change the .flaskenv
cp flaskenv_mode .flaskenv

sed -i "s/MYSQL_HOST=host/MYSQL_HOST=$MYSQL_HOST/g" .flaskenv && \
sed -i "s/MYSQL_PORT=port/MYSQL_PORT=$MYSQL_PORT/g" .flaskenv && \
sed -i "s/MYSQL_DATABASE=database/MYSQL_DATABASE=$MYSQL_DATABASE/g" .flaskenv && \
sed -i "s/MYSQL_USERNAME=name/MYSQL_USERNAME=$MYSQL_USERNAME/g" .flaskenv && \
sed -i "s/MYSQL_PASSWORD=password/MYSQL_PASSWORD=$MYSQL_PASSWORD/g" .flaskenv && \
sed -i "s/REDIS_HOST=host/REDIS_HOST=$REDIS_HOST/g" .flaskenv && \
sed -i "s/REDIS_PORT=port/REDIS_PORT=$REDIS_PORT/g" .flaskenv

if [ $? -eq 0 ]; then
    echo "Mysql and Redis setting done!"
else
    echo "Error: fail to init, please check the .flaskenv"
fi
